package com.zzh.controller.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class ProjectInterceptor implements HandlerInterceptor {
    /**
     * 原始方法调用前执行的内容
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //追踪每个请求的完整生命周期
        String requestId = UUID.randomUUID().toString();
        request.setAttribute("requestId", requestId);
        System.out.println("[" + requestId + "] 原始方法调用前执行的内容preHandle...");
        return true;
    }

    /**
     * 原始方法调用后执行的内容
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String requestId = (String) request.getAttribute("requestId");
        System.out.println("[" + requestId + "] 原始方法调用后执行的内容postHandle...");
    }

    /**
     * 原始方法调用完成后执行的内容
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String requestId = (String) request.getAttribute("requestId");
        System.out.println("[" + requestId + "] 原始方法调用完成后执行的内容afterCompletion...");

    }
}

